<?php
include("dbconnect.php");

$text = $_POST["keyword"];
//echo("hi".$text."<br>");

$pattern = "/(#|@|\^|\*)(\w|\-)*|\w*\s|\w*/";///[#|@|!]\w*|\w*\s|\w*/g
$parse = null;
$returnValue = preg_match_all($pattern, $text, $parse);
//print_r($parse);

$search = "SELECT r.rid, r.html
		FROM records AS r
		JOIN record_tag AS rt
			ON r.rid=rt.rid
		JOIN tags AS t
			ON rt.tid=t.tid
		WHERE r.version=1 AND";
$tagArray = array();

foreach ($parse[0] as $term){
	//handle tags
	//echo $term."<br>";
	if (strpbrk($term, '#@^*')){
		//check database for tag
		//insert on duplicate key
		$type = substr($term, 0, 1);
		$tag = substr($term, 1);
		
		if($tag != ""){
			$search = $search." t.type='".$type."' AND t.tag='".$tag."'";
		}else{
			$search = $search." t.type='".$type."'";
		}			
		

	}//handle words and spaces
	else{
		//add to html
		$search = $search.$term;
	}		
	
}

//echo $search;

//put records in array
//create calender array
$searchArray=array();
$count=0;

$result = mysql_query($search) or die('Query failed: ' . mysql_error());
while($l = mysql_fetch_array($result, MYSQL_ASSOC)) {
	$searchArray[] = [
		'id'=>$l[rid],
		'html'=>$l[html]
	];
	//echo $l[html];
	$count = $count+1;
}
$searchArray[id]=$count;
//print_r($searchArray);
//encode array
echo json_encode($searchArray, JSON_UNESCAPED_SLASHES);
?>